from config.config import *
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

"""
页面基类
"""


class BasePage:
    """所有的页面基类"""

    def __init__(self, driver):
        self.timeout = 10
        self.driver = driver
        # 先检查子类是否设置了url,hasattr内置函数检查对象是否具有指定的属性或方法
        if hasattr(self, 'url'):
            self.url = f"http://{HOST}{self.url}"
        else:
            self.url = None

    def open(self):
        """打开操作的网页"""
        if not self.url:
            raise ValueError("URL未设置，请在子类中定义url属性")
        self.driver.get(self.url)
        self.wait_for_page_loaded()

    def wait_for_page_loaded(self, timeout=None):
        """等待页面完全加载"""
        if timeout is None:
            timeout = self.timeout

        WebDriverWait(self.driver, timeout).until(
            lambda driver: driver.execute_script("return document.readyState") == "complete"
        )

    def find_element(self, locator, timeout=None):
        """
        自定义元素查找方法（带等待）
        :param locator: 元素定位器元组，如 (By.ID, "username")
        :param timeout: 超时时间
        :return: 已查到的元素
        """
        if timeout is None:
            timeout = self.timeout

        try:
            return WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located(locator)
            )
        except TimeoutException:
            raise Exception(f"元素未找到: {locator}")

    def send_keys(self, locator, content):
        """
        自定义输入内容方法
        :param locator: 元素定位器元组
        :param content: 输入内容
        :return: 无
        """
        element = self.find_element(locator)
        element.clear()
        element.send_keys(content)

    def click(self, locator):
        """
        自定义点击方法
        :param locator: 元素定位器元组
        :return: 无
        """
        element = self.find_element(locator)
        element.click()

    def switch_to_frame(self, locator_or_element):
        """
        iframe切换
        :param locator_or_element: 定位器元组或元素对象
        :return: 无
        """
        if isinstance(locator_or_element, tuple):
            frame_el = self.find_element(locator_or_element)
            self.driver.switch_to.frame(frame_el)
        else:
            self.driver.switch_to.frame(locator_or_element)

    def switch_to_default(self):
        """切换回默认内容"""
        self.driver.switch_to.default_content()

    def switch_to_alert_accpet(self):
        '''这是切换弹窗页面，点击确认方法'''
        self.driver.switch_to.alert.accept()
